package dyl.sys.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import dyl.common.util.DylSqlUtil;
import dyl.common.util.JdbcTemplateUtil;
import dyl.sys.bean.SysRoleUser;
import dyl.sys.bean.SysUser;
/**

 * @author Dyl
 * 2017-04-06 17:12:57
 */
@Service
public class SysRoleUserServiceImpl {
	@Resource
	private JdbcTemplateUtil jdbcTemplate;
	/**
	 * 说明：更新角色权限
	 * @return int >0代表操作成功
	 */
	@Transactional
	public int[] updateSysRoleUser(BigDecimal userId,String[] roleIds,SysUser loginUser) throws Exception{
		//1.清空用户原有角色
		jdbcTemplate.update("delete from sys_role_user where userid = ?",new Object[]{userId});
		//2.批量更新用户角色
		String sql = "insert into sys_role_user(id,roleid,userid,creator) values("+DylSqlUtil.getnextSeqNextVal()+",?,?,?)";
		List<Object[]> para = new ArrayList<Object[]>();
		for (int i = 0; i < roleIds.length; i++) {
			para.add(new Object[]{roleIds[i],userId,loginUser.getId()});
		}
		return jdbcTemplate.batchUpdate(sql,para);
	}
	/**
	 * 查询用户所属角色集合
	 * @param userId
	 * @return
	 */
	public List<SysRoleUser> querySysRoleUserList(BigDecimal userId){
		return jdbcTemplate.queryForListBean("select * from sys_role_user where userid = ? ",new Object[]{userId},SysRoleUser.class);
	}
	/**
	 * 删除用户角色
	 * @param userId
	 * @return
	 */
	@Transactional
	public int deleteUserRoles(BigDecimal userId){
		return jdbcTemplate.update("delete from sys_role_user where userid = ?",new Object[]{userId});
	}
}
